package com.blog.servlet;

import com.blog.dao.UserDao;
import com.blog.dao.impl.UserDaoImpl;
import com.blog.entity.User;
import com.blog.util.StringUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * 用户登录Servlet
 */
@WebServlet("/login")  // 配置访问路径
public class LoginServlet extends HttpServlet {
    // 创建DAO对象（数据访问层）
    private UserDao userDao = new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // GET请求跳转到登录页面
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 设置请求编码（防止中文乱码）
        request.setCharacterEncoding("UTF-8");

        // 2. 获取表单参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 3. 参数校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            request.setAttribute("errorMsg", "用户名和密码不能为空！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return; // 终止后续执行
        }

        // 4. 调用DAO层查询用户
        User user = userDao.findByUsername(username);

        // 5. 验证用户
        if (user == null) {
            request.setAttribute("errorMsg", "用户名不存在！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 6. 验证密码（实际开发中应该使用加密比较，这里简化处理）
        if (!password.equals(user.getPassword())) {
            request.setAttribute("errorMsg", "密码错误！");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }

        // 7. 更新最后登录时间
        userDao.updateLastLoginTime(user.getId());

        // 8. 将用户信息存入Session（标记用户已登录）
        HttpSession session = request.getSession();
        session.setAttribute("loginUser", user);

        // 9. 重定向到首页
        response.sendRedirect(request.getContextPath() + "/index.jsp");
    }
}